package com.zhugang.week01;


/**
 * @program algorithms
 * @description: rorate
 * @author: chanzhugang
 * @create: 2022/03/30 22:52
 */
public class Rorate {

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6,}, {7, 8, 9}};
        Rorate rorate = new Rorate();
        rorate.rorate2(matrix);

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix.length; j++) {
                System.out.println(matrix[i][j]);
            }
            System.out.println("\n");
        }
    }

    /**
     * 旋转图像
     * 1 2 3           7 4 1
     * 4 5 6    ==>    8 5 2
     * 7 8 9           9 6 3
     * <p>
     * (i,j)  ==> (j,n-i-1)
     */

    /**
     * 借助辅助数组
     *
     * @param matrix
     */
    public void rorate(int[][] matrix) {
        int n = matrix.length;
        int[][] temp = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                temp[j][n - i - 1] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = temp[i][j];
            }
        }
    }

    /**
     * 翻转代替旋转
     *
     * @param matrix
     */
    public void rorate2(int[][] matrix) {
        int n = matrix.length;
        // 先上下翻转
        for (int i = 0; i < n / 2; i++) {
            for (int j = 0; j < n; j++) {
                swap(matrix, i, j, n - i - 1, j);
            }
        }
        // 在对角翻转
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                swap(matrix, i, j, j, i);
            }
        }
    }

    /**
     * 交换位置
     *
     * @param matrix
     * @param i
     * @param j
     * @param p
     * @param q
     */
    private void swap(int[][] matrix, int i, int j, int p, int q) {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[p][q];
        matrix[p][q] = temp;
    }

    /**
     * 原地旋转：太复杂，暂时不做
     */
    public void rorate3(int[][] matrix) {

    }

}